import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.StringTokenizer;

import javax.servlet.http.*;  // provides servlet functionality
import javax.servlet.*;	      // ditto
import javax.*;

public class Confirmation extends HttpServlet {
	
	private final static String REDIRECT_TO_LOGIN_CODE 
	= "<meta http-equiv=\"REFRESH\" content=\"2;url=../Login.jsp\">";
	
	private final static String REDIRECT_TO_CUSTOMER_INFORMATION_CODE 
	= "<meta http-equiv=\"REFRESH\" content=\"5;url=CustomerInformation\">";
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
	throws IOException, ServletException
	{
		System.out.println("---Doing Post in CustomerInformation---\n");
		
		if (!Bridge.hasBeenToMainPage(request.getSession(), response.getWriter()))
		{
			return;
		}
		
		PrintWriter out = response.getWriter();
		ArrayList<DVD> dvds = new ArrayList<DVD>();
		CartOfItems cart = null;
		
		HttpSession session = request.getSession();
		
		Boolean customerInfoGood = (Boolean) session.getAttribute(Constants.customerInfoGoodAttributeName);
		if (customerInfoGood == null || !customerInfoGood.booleanValue()) // customer needs to update info
		{
			out.print("<html><head><title>Redirecting...</title>"
					+ REDIRECT_TO_LOGIN_CODE + "</head>"
					+ "<body><font color=\"red\">There's a problem with your information.<br>" +
							"Your order was <b>NOT</b> processesd.<br>" +
							"Please update it before purchasing.</font></body>" 
					+"</html>");
			return;
		}
		
		StringBuffer body = new StringBuffer("");
					
		//for debugging
		Enumeration<String> paramNames = request.getParameterNames();
		while (paramNames.hasMoreElements())
		{
			String paramName = paramNames.nextElement();
			System.out.println(paramName + "=" + request.getParameter(paramName));
		}
				
		try
		{
			Class.forName("org.postgresql.Driver").newInstance();
			Connection connection = DriverManager.getConnection(
				"jdbc:postgresql://localhost/fabflixs", "testuser", "testpass");	
			
			String user = (String)session.getAttribute(Constants.loggedInUserAttributeName);
			if (user == null)
			{
				// the user needs to log in first!
				// this should never be reached, but just in case
				out.print("<html><head><title>Redirecting...</title>"
						+ REDIRECT_TO_LOGIN_CODE + "</head>"
						+ "<body>You need to log in first...</body>" 
						+"</html>");
				return;
			}
			
			Statement select = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
			ResultSet result = select.executeQuery("Select * from customers WHERE email = \'" + user + "\'");
			
			int customer_id;
			//get info for the customer
			if (result.next())
			{
				customer_id = result.getInt("id");
				String firstName = result.getString(2);
				String lastName = result.getString(3);
				String shippingAddress = (String) session.getAttribute(Constants.shippingAddressAttributeName);
								
				body.append("<h1>" + firstName + " " + lastName + ", your order has been confirmed and will be shipped to:<br>");
				body.append("<h1><b>" + shippingAddress + "</b><br></h1>");
				body.append("<h1><b><font color=\"blue\">Thank you for shopping with FabFlixs!</font></h1>");
				
				// update the sales table
				Statement select2 = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
				ResultSet result2 = select2.executeQuery("Select * from sales");
				
				cart = ((CartOfItems)session.getAttribute(Constants.cartAttributeName));
				if (cart != null)
					dvds = cart.getAllDvds();
				
				
				Statement select3 = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
				ResultSet result3 = select3.executeQuery("Select max(id) from sales");				
				
				result3.next();
				int purchaseId = result3.getInt(1) + 1;
				System.out.println("starting purchaseId=" + purchaseId);
				
				for (int i = 0; i < dvds.size(); i++)
				{
					System.out.println("Time " + i + " through the insertion loop.");
					if (i == 0)	result2.moveToInsertRow();
					result2.updateInt("customer_id", customer_id);
					result2.updateInt("movie_id", dvds.get(i).getID());
					result2.updateTimestamp("time", new java.sql.Timestamp(System.currentTimeMillis()));
					result2.updateInt("quantity_ordered", dvds.get(i).getQuantity());
					result2.updateString("shipping_address", shippingAddress);
					result2.updateInt("id", purchaseId);
					purchaseId++;
					
					result2.insertRow();
				}
				
				//clear the cart when we're done
				session.removeAttribute(Constants.cartAttributeName);
			}
			
			
			
			body.append("<h2>Please print this order confirmation page for your records.</h2>");
			//print out the current cart, with the prices and total cost
			body.append(printCartWithPrices(dvds));	
			
			body.append("<TABLE bgcolor=\"#FFFFFF\" border=0 bordercolorlight=\"#C0C0C0\" bordercolordark=\"#808080\">");
			body.append("<TR valign=top>");
			body.append("<TD align=right width=450>");
			body.append("<a href=\"../Search.jsp\">");
			body.append("<div id=\"Next\" \"><input type=\"image\" name=\"Next\" src=\"../images/SearchEnd.png\"></div></a>");
			body.append("</TD>");
			body.append("<TD  width=20>");
			body.append("<div> </div>");
			body.append("</TD>");
			body.append("<TD align=left width=450>");
			body.append("<a href=\"../Browse.jsp\">");
			body.append("<div id=\"Next\" \"><input type=\"image\" name=\"Next\" src=\"../images/BrowseEnd.png\"></div></a>");
			body.append("</TD>");
			body.append("</TR>");
			body.append("</TABLE>");
			
			//body.append("<form name=\"mainPageForm\" action=\"../Main_Page.jsp\" method=\"GET\">");
			//body.append("<input align=\"center\" type=\"image\" name=\"MainPageButton\" src=\"../images/MainPage.png\">");
			//body.append("</form>");
						
		} catch (Exception e) 
		{
			out.println("Exception: " + e.getMessage());
			e.printStackTrace();
		}		
		
		out.print(Template.getTemplateHTML("Order Confrimation", body.toString(),
				Constants.noCheckoutButton, session  ));
	}
	
	private String printCartWithPrices(ArrayList<DVD> dvds)
	{
		StringBuffer buf = new StringBuffer();
		
		//buf.append("<form name=\"cartForm\" action=\"DvdProcessor\" method=\"GET\">");
		//out.println("<div align=\"left\"><br>");
		
		//making table
	
		buf.append("<div><TABLE bgcolor=\"#FFFFFF\" border=1 bordercolorlight=\"#C0C0C0\" bordercolordark=\"#808080\">");
		
		buf.append("<TR valign=top>");	
	
		buf.append("<TD width=150><div class=\"wpmd\">");
		buf.append("<div>");
		buf.append("<B>TITLE</B>");
		buf.append("</div>");
		buf.append("</TD>");		
		
		buf.append("<TD width=100><div class=\"wpmd\">");
		buf.append("<div>");
		buf.append("<B>YEAR</B>");
		buf.append("</div>");
		buf.append("</TD>");
		
		buf.append("<TD width=150><div class=\"wpmd\">");
		buf.append("<div>");
		buf.append("<B>DIRECTOR</B>");
		buf.append("</div>");
		buf.append("</TD>");
		
		buf.append("<TD width=150><div class=\"wpmd\">");
		buf.append("<div>");
		buf.append("<B>QUANTITY</B>");
		buf.append("</div>");
		buf.append("</TD>");
				
		buf.append("<TD width=150><div class=\"wpmd\">");
		buf.append("<div>");
		buf.append("<B>PRICE</B>");
		buf.append("</div>");
		buf.append("</TD>");
		buf.append("</TR>");
		
		Price totalPrice = new Price(0);
		
		for (int i = 0; i < dvds.size(); i++)
		{
			//title
			buf.append("<TR valign=top>");
			buf.append("<TD width=150><div class=\"wpmd\">");
			buf.append("<div>");
			buf.append( dvds.get(i).getTitle() );
			buf.append("</div>");
			buf.append("</TD>");
			
			//year
			buf.append("<TD width=100><div class=\"wpmd\">");
			buf.append("<div>");
			buf.append( dvds.get(i).getYear() );
			buf.append("</div>");
			buf.append("</TD>");
			
			//director's name
			buf.append("<TD width=150><div class=\"wpmd\">");
			buf.append("<div>");
			buf.append( dvds.get(i).getDirectorName() );
			buf.append("</div>");
			buf.append("</TD>");
			
			// quantity
			buf.append("<TD width=150><div class=\"wpmd\">");
			buf.append("<div>");
			buf.append(dvds.get(i).getQuantity() );
			buf.append("</div>");
			buf.append("</TD>");
			totalPrice.addPrice( dvds.get(i).getPrice() );
			
			// price
			buf.append("<TD width=150><div class=\"wpmd\">");
			buf.append("<div>");
			buf.append( dvds.get(i).getPrice().toString() );
			buf.append("</div>");
			buf.append("</TD>");
			
			buf.append("</TR>");
		}
		
		buf.append("<TR valign=top>");
		buf.append("</TR>");
		buf.append("<TR valign=top>");
		buf.append("<TD width=150><div class=\"wpmd\">");
		buf.append("</TD>");
		buf.append("<TD width=100><div class=\"wpmd\">");
		buf.append("</TD>");
		buf.append("<TD width=100><div class=\"wpmd\">");
		buf.append("</TD>");
		buf.append("<TD width=150><div class=\"wpmd\">");
		buf.append("<B>TOTAL PRICE:</B>");
		buf.append("</TD>");
		buf.append("<TD width=200><div class=\"wpmd\">");
		buf.append("<B><font color=\"green\">" + totalPrice + "</font></B>" );
		buf.append("</TD>");
		buf.append("</TR>");
		
		buf.append("</TABLE>");

		//buf.append("</form>");
		
		return buf.toString();
	}
	
	private static boolean isNumber(String number)
	{
		try 
		{
		
			int num = Integer.parseInt(number);
		}
		catch(NumberFormatException e)
		{
			return false;
		}
		return true;
	}
	
	private int getTotalQuantity(ArrayList<DVD> dvds)
	{
		int total = 0;
		
		for (int i = 0; i < dvds.size(); i++)
		{
			total += dvds.get(i).getQuantity();
		}
		
		return total;
	}	
	
}